<?php

namespace App\Http\Controllers\Api;

use App\Models\Book;
use App\Models\SellCart;
use App\Models\SellOrder;
use App\Models\SellOrderItem;
use App\Models\SysConfig;
use GuzzleHttp\Client;
use Illuminate\Http\Request;

class SellCartController extends BaseController
{
    public function checkIsbn(Request $request)
    {
        $isbn = trim($request->get('isbn'));
        if(empty($isbn))
        {
            return $this->err(1,200,'','参数错误');
        }

        if(!preg_match("/^\d{10}$/",$isbn) && !preg_match("/^\d{13}$/",$isbn))
        {
            return $this->err(1,200,'','条形码格式有误，请重新输入');
        }


        $items = [];
        $books_num = Book::query()->where('isbn',$isbn)->where('deleted',0)->where('is_recycle',1)->count();
        if($books_num > 1)
        {
            $books = Book::query()->select(['id','title','image','author','recyle_price','is_sult','publish_house','publish_time','old_price'])->where('isbn',$isbn)->where('deleted',0)->where('is_recycle',1)->get();

            //判断是否已经卖过
            $sell_orders = SellOrder::query()->select(['id','state'])->where('user_id',$this->user_id)->where('state','>=',3)->get();
            $sell_order_ids = [];
            if($sell_orders->isNotEmpty())
            {
                foreach ($sell_orders as $s)
                {
                    $sell_order_ids[] = $s->id;
                }
            }

            foreach ($books as $v)
            {
                $row = SellCart::query()->where('type',1)->where('book_id',$v->id)->where('user_id',$this->user_id)->first();
                if(!empty($row))
                {
                    return $this->err(1,200,'','你已经添加过《'.$v->title.'》这本书了，换一本吧');
                }


                $sell_order_item = SellOrderItem::query()->select(['sell_order_id','book_id'])->where('state','!=',3)->whereIn('sell_order_id',$sell_order_ids)->where('user_id',$this->user_id)->where('book_id',$v->id)->orderBy('id','desc')->first();
                if(!empty($sell_order_item))
                {
                    return $this->ok([],'这本书《'.$v->title.'》你已经卖过一本了，我们暂不支持个人用户反复卖同一本书。如您有大量图书要售卖，可联系快鱼客服，添加客服微信号：kuaiyu-kefu',1001);
                }

                $items[] = [
                    'book_id'           => $v['id'],
                    'book_image'        => $v['image'],
                    'book_title'        => $v['title'],
                    'book_author'       => $v['author'],
                    'publish_house'     => $v['publish_house'],
                    'publish_time'      => $v['publish_time'],
                    'old_price'         => $v['old_price'],
                ];
            }

            $data['items'] = $items;
            return $this->ok($data);
        }


        $book = Book::query()->select(['id','title','image','author','recyle_price','is_recycle','is_sult'])->where('isbn',$isbn)->where('deleted',0)->first();
        if(!empty($book))
        {
            $row = SellCart::query()->where('type',1)->where('book_id',$book->id)->where('user_id',$this->user_id)->first();
            if(!empty($row))
            {
                return $this->err(1,200,'','你已经添加过这本书了，换一本吧');
            }

            //判断是否已经卖过
            $sell_orders = SellOrder::query()->select(['id','state'])->where('user_id',$this->user_id)->where('state','>=',3)->get();

            $sell_order_ids = [];
            if($sell_orders->isNotEmpty())
            {
                foreach ($sell_orders as $s)
                {
                    $sell_order_ids[] = $s->id;
                }
            }

            $sell_order_item = SellOrderItem::query()->select(['sell_order_id','book_id'])->where('state','!=',3)->whereIn('sell_order_id',$sell_order_ids)->where('user_id',$this->user_id)->where('book_id',$book->id)->orderBy('id','desc')->first();

            if(!empty($sell_order_item))
            {
                return $this->ok([],'这本书你已经卖过一本了，我们暂不支持个人用户反复卖同一本书。如您有大量图书要售卖，可联系快鱼客服，添加客服微信号：kuaiyu-kefu',1001);
                //$sell_order = SellOrder::query()->select(['id','state'])->where('id',$sell_order_item->sell_order_id)->first();
                //if($sell_order->state >= 3)
                //{
                    //return $this->ok([],'这本书你已经卖过一本了，我们暂不支持个人用户反复卖同一本书。如您有大量图书要售卖，可联系快鱼客服，添加客服微信号：kuaiyu-kefu',1001);
                //}
            }

            $insert_data = [
                'user_id'       => $this->user_id,
                'book_id'       => $book->id,
                'from'          => 1,
                'book_image'    => $book->image,
                'book_title'    => $book->title,
                'book_author'   => $book->author,
                'recyle_price'  => $book->recyle_price,
                'created_at'    => $this->time,
            ];
            //库中有该书
            if($book->is_recycle == 2)
            {
                //未设置回收
                $row = SellCart::query()->where('type',0)->where('book_id',$book->id)->where('user_id',$this->user_id)->first();
                if(empty($row))
                {
                    $insert_data['type'] = 0;
                    SellCart::create($insert_data);
                }
                return $this->ok([],'抱歉，平台暂时不收这本书！我们会根据市场及库存情况动态调整收书范围。');
                //return $this->err(1,200,'','抱歉，平台暂时不收这本书！我们会根据市场及库存情况动态调整收书范围。');
            }

            if($book->is_sult)
            {
                $insert_data['type'] = 1;
                SellCart::create($insert_data);
                return $this->ok(['is_sult' => $book->is_sult],'这是套装书，只需扫一本即可');
            }

            $insert_data['type'] = 1;
            SellCart::create($insert_data);
            return $this->ok();
        }
        else
        {
            $client = new Client();
            $query = array_filter([
                'key' => '4d9f2e774671f575cdcb1d7c20f020b8',
                'sub' => $isbn,
            ]);
            $url = 'http://feedback.api.juhe.cn/ISBN';
            $response = $client->get($url, [
                'query' => $query,
            ])->getBody()->getContents();
            $response = json_decode($response, true);
            //dd($response);
            if(empty($response['result']))
            {
                return $this->ok([],'未匹配到有效结果，条形码无效或错误请换一本试试。');
                //return $this->err(1,200,'','未匹配到有效结果，条形码无效或错误请换一本试试。');
            }
            else
            {
                if(empty($response['result']['title']))
                {
                    return $this->ok([],'抱歉，平台暂时不收这本书！我们会根据市场及库存情况动态调整收书范围。');
                }


                $insert_data = [
                    'user_id'       => $this->user_id,
                    'book_id'       => 0,
                    'from'          => 2,
                    'book_image'    => $response['result']['images_large'],
                    'book_title'    => $response['result']['title'],
                    'book_author'   => $response['result']['author'],
                    'created_at'    => $this->time,
                    'type'          => 0,
                ];

                $levelNum = $response['result']['levelNum'];  //推荐指数
                $pubdate = $response['result']['pubdate'];  //出版时间
                $price = $response['result']['price'];

                $recyle_price = 0;
                if($levelNum >= 7 && $levelNum < 7.5)
                {
                    $recyle_price = $price*0.1;
                }
                elseif($levelNum >= 7.5 && $levelNum < 8)
                {
                    $recyle_price = $price*0.12;
                }
                elseif($levelNum >= 8 && $levelNum < 8.5)
                {
                    $recyle_price = $price*0.14;
                }
                elseif($levelNum >= 8.5 && $levelNum <= 10)
                {
                    $recyle_price = $price*0.16;
                }

                $recyle_price = round($recyle_price,1);
                if(empty($recyle_price) || $recyle_price == '0.0')
                {
                    $recyle_price = 5.0;
                }

                $book = Book::query()->where('from',2)->where('deleted',0)->where('isbn',$isbn)->first();
                if(empty($book))
                {
                    $params = [
                        'category_pid'                  => 0,
                        'category_ids'                  => '',
                        'title'                         => isset($response['result']['title']) ? $response['result']['title'] : '',
                        'author'                        => isset($response['result']['author']) ? $response['result']['author'] : '',
                        'sub_title'                     => !empty($response['result']['subtitle']) ? $response['result']['subtitle'] : '',
                        'score'                         => 0,
                        'image'                         => !empty($response['result']['images_large']) ? $response['result']['images_large'] : '',
                        'author_intro'                  => '',
                        'publish_house'                 => !empty($response['result']['publisher']) ? $response['result']['publisher'] : '',
                        'publish_time'                  => !empty($response['result']['pubdate']) ? $response['result']['pubdate'] : '',
                        'publish_num'                   => '',
                        'publish_translator'            => '',
                        'publish_package'               => '',
                        'publish_paper'                 => '',
                        'publish_pages'                 => '',
                        'publish_open'                  => '',
                        'isbn'                          => $isbn,
                        'desc'                          => '',
                        'catalog'                       => '',
                        'old_price'                     => $response['result']['price'],
                        'new_book_price'                => 0.00,
                        'new_book_stock'                => 0,
                        'good_book_price'               => 0.00,
                        'good_book_stock'               => 0,
                        'medium_book_price'             => 0.00,
                        'medium_book_stock'             => 0,
                        'is_recycle'                    => 1,
                        'is_sult'                       => 0,
                        'recyle_price'                  => $recyle_price ? $recyle_price : 0.0,
                        'homepage_recommend_module_ids' => '',
                        'state'                         => 2,
                        'created_at'                    => $this->time,
                        'updated_at'                    => $this->time,
                        'total_stock'                   => 0,
                        'new_book_discount'             => 0,
                        'good_book_discount'            => 0,
                        'medium_book_discount'          => 0,
                        'score_num'                     => 0,
                        'deleted'                       => 0,
                        'from'                          => 2,
                    ];
                }

                if(empty($response['result']['price']))
                {
                    $params['is_recycle'] = 2;
                    $book = Book::create($params);
                    return $this->ok([],'抱歉，平台暂时不收这本书！我们会根据市场及库存情况动态调整收书范围。');
                }

                if(empty($pubdate))
                {
                    $params['is_recycle'] = 2;
                    $book = Book::create($params);
                    return $this->ok([],'抱歉，平台暂时不收这本书！我们会根据市场及库存情况动态调整收书范围。');
                }

                $pubyear = 0;
                if(!empty($pubdate))
                {
                    $pubyear = date('Y',strtotime($pubdate));
                }
                //dd($pubdate);
                if($price > 300 || $pubyear < 2005 || $levelNum < 7 || strpos($response['result']['publisher'],'教育') || strpos($response['result']['publisher'],'大学') || empty($response['result']['author']) || empty($levelNum) || empty($response['result']['publisher']))
                {
                    $params['is_recycle'] = 2;
                    //var_dump($params);die;
                    $book = Book::create($params);

                    $insert_data['book_id']         = $book->id;
                    $insert_data['recyle_price']    = $recyle_price;
                    $insert_data['book_title']      = $response['result']['title'];
                    $insert_data['book_author']     = $response['result']['author'];

                    $row = SellCart::query()->where('type',0)->where('book_id',$book->id)->where('user_id',$this->user_id)->first();
                    if(empty($row))
                    {
                        SellCart::create($insert_data);
                    }
                    return $this->ok([],'抱歉，平台暂时不收这本书！我们会根据市场及库存情况动态调整收书范围。');
                }

                //dd($recyle_price);
                $book = Book::create($params);
                $book_id = $book->id;

                $row = SellCart::query()->where('type',1)->where('book_id',$book_id)->where('user_id',$this->user_id)->first();
                if(empty($row))
                {
                    $insert_data['type']            = 1;
                    $insert_data['book_id']         = $book_id;
                    $insert_data['recyle_price']    = $recyle_price;
                    $insert_data['book_title']      = $response['result']['title'];
                    $insert_data['book_author']     = $response['result']['author'];
                    SellCart::create($insert_data);
                    return $this->ok();
                }
                return $this->ok([],'抱歉，平台暂时不收这本书！我们会根据市场及库存情况动态调整收书范围。');
            }
        }
    }

    public function addCart(Request $request)
    {
        $book_id = intval($request->get('book_id'));
        if(empty($book_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $book = Book::query()->where('id',$book_id)->where('deleted',0)->where('is_recycle',1)->first();
        if(empty($book))
        {
            return $this->err(1,200,'','请选择正确的图书');
        }

        $row = SellCart::query()->where('type',1)->where('book_id',$book->id)->where('user_id',$this->user_id)->first();
        if(!empty($row))
        {
            return $this->err(1,200,'','你已经添加过这本书了，换一本吧');
        }

        $insert_data = [
            'user_id'       => $this->user_id,
            'book_id'       => $book->id,
            'from'          => 1,
            'book_image'    => $book->image,
            'book_title'    => $book->title,
            'book_author'   => $book->author,
            'recyle_price'  => $book->recyle_price,
            'created_at'    => $this->time,
            'type'          => 1,
        ];
        SellCart::create($insert_data);

        return $this->ok([]);
    }

    public function getCartConfig()
    {
        $sysConfigModel = new SysConfig();
        $result = $sysConfigModel->getSellCartConfig();
        return $this->ok($result);
    }

    public function index()
    {
        $carts = SellCart::query()->where('user_id',$this->user_id)->get();
        if($carts->isNotEmpty())
        {
            foreach ($carts as $v)
            {
                if($v->book_id > 0)
                {
                    $book = Book::query()->select(['id','is_recycle','recyle_price','state','deleted'])->where('id',$v->book_id)->first();

                    if(empty($book))
                    {
                        continue;
                    }

                    if($book->is_recycle == 1 && $book->deleted == 0)
                    {
                        SellCart::query()->where('id',$v->id)->update(['type' => 1,'recyle_price' => $book->recyle_price]);
                    }
                    else
                    {
                        SellCart::query()->where('id',$v->id)->update(['type' => 0]);
                    }
                }
            }
        }


        $result['can_recycle_books'] = [];
        $result['not_recycle_books'] = [];

        $books1 = SellCart::query()->where('user_id',$this->user_id)->where('type',1)->orderBy('id','desc')->get();
        if(!empty($books1))
        {
            foreach ($books1 as $v)
            {
                $result['can_recycle_books'][] = [
                    'id'            => $v->id,
                    'book_id'       => $v->book_id,
                    'book_title'    => $v->book_title,
                    'book_author'   => $v->book_author,
                    'book_image'    => $v->book_image,
                    'recyle_price'  => $v->recyle_price,
                ];
            }
        }

        $books2 = SellCart::query()->where('user_id',$this->user_id)->where('type',0)->orderBy('id','desc')->get();
        if(!empty($books2))
        {
            foreach ($books2 as $v)
            {
                $result['not_recycle_books'][] = [
                    'id'                    => $v->id,
                    'book_title'            => $v->book_title,
                    'book_author'           => $v->book_author,
                    'book_image'            => $v->book_image,
                    'is_feedback_recyle'    => $v->is_feedback_recyle,
                ];
            }
        }

        return $this->ok($result);
    }

    public function destroy(Request $request)
    {
        $id = intval($request->get('id'));
        if(empty($id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $row = SellCart::find($id);
        if(empty($row) || $row->user_id != $this->user_id)
        {
            return $this->err(1,200,'','记录不存在');
        }

        $ret = SellCart::destroy($id);
        if($ret)
        {
            return $this->ok([]);
        }
        return $this->err(1,200,'','删除失败');
    }
}
